package com.shiguo365.market.display.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.shiguo365.market.R;
import com.shiguo365.market.application.MyApplication;
import com.shiguo365.market.bean.Product;
import com.shiguo365.market.display.activity.ProductListActivity;
import com.shiguo365.market.display.util.RefreshUtils;
import com.shiguo365.market.display.util.ToastUtils;
import com.shiguo365.market.display.view.ISearchView;
import com.shiguo365.market.presenter.contract.ISearchPresenter;
import com.shiguo365.market.presenter.implement.SearchPresenter;
import com.yalantis.phoenix.PullToRefreshView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by caomenglong on 16/7/6.
 */
public class SearchFragment extends Fragment implements ISearchView,PullToRefreshView.OnRefreshListener,AdapterView.OnItemClickListener{
    private String TAG="SearchFragment";
    private EditText mEtSearch = null;// 输入搜索内容
    private Button mBtnClearSearchText = null;// 清空搜索信息的按钮
    private LinearLayout mLayoutClearSearchText = null;
    private List<Map> jsonObjectList=new ArrayList<Map>();
    PullToRefreshView mPullToRefreshView;
    private ISearchPresenter searchPresenter;
    private Fragment fragment;
    private ListView listView;


    private List<String> listdata =new ArrayList<String>();
    private List<String> listkeydata =new ArrayList<String>();

    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_search, container, false);
        fragment  = this;
        searchPresenter=new SearchPresenter(this,this);
        searchPresenter.getAllTags();

        mEtSearch = (EditText) view.findViewById(R.id.et_search);
        mBtnClearSearchText = (Button) view.findViewById(R.id.btn_clear_search_text);
        mLayoutClearSearchText = (LinearLayout) view.findViewById(R.id.layout_clear_search_text);

        mEtSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int textLength = mEtSearch.getText().length();
                if (textLength > 0) {
                    mLayoutClearSearchText.setVisibility(View.VISIBLE);
                } else {
                    mLayoutClearSearchText.setVisibility(View.GONE);
                }
            }
        });

        mBtnClearSearchText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtSearch.setText("");
                mLayoutClearSearchText.setVisibility(View.GONE);
            }
        });
        mEtSearch.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View arg0, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    Toast.makeText(view.getContext(),
                            mEtSearch.getText().toString().trim(),
                            Toast.LENGTH_LONG).show();

                    String searchName=mEtSearch.getText().toString().trim();
                    Intent intent = new Intent(fragment.getActivity().getApplicationContext(), ProductListActivity.class);
                    intent.putExtra("searchName",searchName);
                    intent.putExtra("action","search");
                    startActivity(intent);
                }
                return false;
            }
        });

        //list
        listView=(ListView) view.findViewById(R.id.listView);

        listView.setOnItemClickListener(this);


        //*********刷新功能
        mPullToRefreshView = (PullToRefreshView) view.findViewById(R.id.pull_to_refresh);
        mPullToRefreshView.setOnRefreshListener(this);


        RefreshUtils.initOnCreate(mPullToRefreshView, this);
        RefreshUtils.refreshOnCreate(mPullToRefreshView, this);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        RefreshUtils.refreshOnCreate(mPullToRefreshView, this);
    }


    @Override
    public void onGetAllTagsOk(@NonNull JSONObject result) {
        listdata.clear();
        listkeydata.clear();
        Set<String> set = result.keySet();
        for(String key : set){
            listdata.add(result.getString(key));
            listkeydata.add(key);
        }
        ArrayAdapter<String> adapter =new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1,listdata);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onGetAllTagsFinish() {
        mPullToRefreshView.setRefreshing(false);
    }

    @Override
    public void onRefresh() {

        Log.d("SearchPresenter","onRefresh");
        listdata.clear();
        listkeydata.clear();
        searchPresenter.getAllTags();

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String tagName =listdata.get(i);
        String tagCode =listkeydata.get(i);
        goToProductActivity(tagName,tagCode);
    }


    private void goToProductActivity(String tagName,String tagCode){
        Intent intent = new Intent(this.getActivity(), ProductListActivity.class);
        intent.putExtra("tagName",tagName);
        intent.putExtra("tagCode",tagCode);
        startActivity(intent);
    }

}
